package com.hc.likelistenmusic.fragment

import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hc.likelistenmusic.R
import com.hc.likelistenmusic.activity.OnlineMusicActivity
import com.hc.likelistenmusic.adapter.OnlineMusicAdapter
import com.hc.likelistenmusic.bean.OnlineMusicResponse
import com.hc.likelistenmusic.util.OkHttpUtil
import com.hc.likelistenmusic.util.OkHttpUtil.ResultCallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class OnlineMusicFragment :LazyFragment(false) {
    lateinit var mOnlineMusicActivity: OnlineMusicActivity
    lateinit var mTv_fom_srolled_top:TextView
    lateinit var mTv_fom_srolled_bottom:TextView
    lateinit var mTv_search_result_empty:TextView
    lateinit var mRv_fom:RecyclerView
    lateinit var mOnlineMusicAdapter: OnlineMusicAdapter
    var mOnlineMusicIdList = mutableListOf<OnlineMusicResponse>()
    var mCurrentSelectedOnlineMusicId = -1
    override fun initView(rootView: View) {
        mOnlineMusicActivity = activity as OnlineMusicActivity
        mTv_fom_srolled_top = rootView.findViewById(R.id.tv_fom_srolled_top)
        mTv_fom_srolled_bottom = rootView.findViewById(R.id.tv_fom_srolled_bottom)
        mTv_search_result_empty = rootView.findViewById(R.id.tv_search_result_empty)
        mRv_fom = rootView.findViewById(R.id.rv_fom)
        mRv_fom.apply {
            layoutManager = LinearLayoutManager(context)
            mOnlineMusicAdapter = OnlineMusicAdapter(context,R.layout.fragment_online_music_rv_item,mOnlineMusicIdList)
            mOnlineMusicAdapter.setOnItemClickListener { om, position ->
               onItemClick(om,position)
            }
            adapter = mOnlineMusicAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener(){
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dy > 0 && !recyclerView.canScrollVertically(1)) {
                        showOrHideTopAndBottom(false)
                    } else if (dy < 0 && !recyclerView.canScrollVertically(-1)) {
                        showOrHideTopAndBottom(true)
                    }
                }
            })
        }
    }

    private fun showOrHideTopAndBottom(top: Boolean) {
        if (top) {
            mTv_fom_srolled_top.visibility = VISIBLE
            CoroutineScope(Dispatchers.IO).launch {
                delay(1000)
                CoroutineScope(Dispatchers.Main).launch {
                    mTv_fom_srolled_top.visibility = View.INVISIBLE
                }
            }
        } else {
            mTv_fom_srolled_bottom.visibility = VISIBLE
            CoroutineScope(Dispatchers.IO).launch {
                delay(1000)
                CoroutineScope(Dispatchers.Main).launch {
                    mTv_fom_srolled_bottom.visibility = View.INVISIBLE
                }
            }
        }
    }

    private fun onItemClick(om: OnlineMusicResponse, position: Int) {
        if(mCurrentSelectedOnlineMusicId==-1){
            mCurrentSelectedOnlineMusicId = om.id
            mOnlineMusicActivity.prepareOnlineMusic(om)
        }else{
            if(mCurrentSelectedOnlineMusicId==om.id){
                if(mOnlineMusicActivity.MediaPlayOrPauseStatus()){
                    mOnlineMusicActivity.MediaPause()
                }else{
                    mOnlineMusicActivity.MediaPlay()
                }
                mOnlineMusicAdapter.notifyItemChanged(position)
            }else{
                mCurrentSelectedOnlineMusicId = om.id
                mOnlineMusicActivity.prepareOnlineMusic(om)
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.fragment_online_music
    }

    fun loadSearchData(searchInfo: CharSequence) {
        mCurrentSelectedOnlineMusicId = -1
        mOnlineMusicIdList.clear()
        val url = "http://192.168.1.5:8088/music/selectByNameOrSinger/${searchInfo}"
        OkHttpUtil.getInstance().requestWithParams(url,true,false,null,null,object :ResultCallback{
            override fun onFailure(message: String) {
                dealResponseFailure()
            }

            override fun onResponseFailure(failureCode: Int, info: String) {
                dealResponseFailure()
            }

            override fun onResponseSuccess(successCode: Int, info: String) {
                dealResponseSuccess(info)
            }
        })
    }

    fun dealResponseFailure() {
        CoroutineScope(Dispatchers.Main).launch {
            mTv_search_result_empty.visibility = VISIBLE
            mRv_fom.visibility = GONE
            mOnlineMusicAdapter.notifyDataSetChanged()
            mOnlineMusicActivity.dismissInfoDialog()
        }
    }

    fun dealResponseSuccess(info: String){
        try {
            val gson = Gson()
            val type = object : TypeToken<List<OnlineMusicResponse>>() {}.type
            val array:List<OnlineMusicResponse> = gson.fromJson(info, type)
            array.forEach {
                mOnlineMusicIdList.add(it)
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
        CoroutineScope(Dispatchers.Main).launch {
            if(mOnlineMusicIdList.isEmpty()){
                mTv_search_result_empty.visibility = VISIBLE
                mRv_fom.visibility = GONE
            }else{
                mTv_search_result_empty.visibility = GONE
                mRv_fom.visibility = VISIBLE
            }
            mOnlineMusicAdapter.notifyDataSetChanged()
            mOnlineMusicActivity.dismissInfoDialog()
        }
    }

    fun clearSearchData() {
        mCurrentSelectedOnlineMusicId = -1
        mOnlineMusicIdList.clear()
        mTv_search_result_empty.visibility = VISIBLE
        mRv_fom.visibility = GONE
        mOnlineMusicAdapter.notifyDataSetChanged()
    }

    fun handChangeNextSong(next: Boolean,show:Boolean) {
        if(!mOnlineMusicIdList.isEmpty()){
            if(mCurrentSelectedOnlineMusicId == -1){
                var om:OnlineMusicResponse
                if(next){
                    om = mOnlineMusicIdList.get(0)
                }else{
                    om = mOnlineMusicIdList.get(mOnlineMusicIdList.size-1)
                }
                mCurrentSelectedOnlineMusicId = om.id
                mOnlineMusicActivity.prepareOnlineMusic(om)
            }else {
                var position = -1
                mOnlineMusicIdList.forEachIndexed { index, onlineMusicId ->
                    if(onlineMusicId.id==mCurrentSelectedOnlineMusicId){
                        position = index
                    }
                }
                if(position==-1){
                    var om:OnlineMusicResponse
                    if(next){
                        om = mOnlineMusicIdList.get(0)
                    }else{
                        om = mOnlineMusicIdList.get(mOnlineMusicIdList.size-1)
                    }
                    mCurrentSelectedOnlineMusicId = om.id
                    mOnlineMusicActivity.prepareOnlineMusic(om)
                }else{
                    var index: Int
                    if(next){
                        index = position+1
                        if(index>mOnlineMusicIdList.size){
                            index = 0
                        }
                    }else{
                        index = position-1
                        if(index<0){
                            index = mOnlineMusicIdList.size-1
                        }
                    }
                    val om = mOnlineMusicIdList.get(index)
                    mCurrentSelectedOnlineMusicId = om.id
                    mOnlineMusicActivity.prepareOnlineMusic(om)
                }
            }
        }else{
            if(show){
                mOnlineMusicActivity.handChangeNextSongError()
            }
        }
    }

}